<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共166条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/employees/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="isShowDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="姓名" prop="username" sortable="">
            <template v-slot="obj">
              <img v-fiximg class="avatar" :src="obj.row.staffPhoto" alt="">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" sortable="" :formatter="formatEmployment" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template v-slot="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template v-slot="obj">
              <!-- 开关组件, 默认绑定布尔值, 但是我们的数据是数字
              需要绑定一个 :active-value 指定 1 才是激活值 -->
              <el-switch
                v-model="obj.row.enableState"
                :active-value="1"
                :inactive-value="0"
                :disabled="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="obj">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${obj.row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="assignRole(obj.row.id)">
                设置角色
              </el-button>
              <el-button type="text" size="small" @click="delEmployee(obj.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            :page-size="pageConfig.size"
            layout="prev, pager, next"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增弹窗 -->
      <AddEmployee :is-show-dialog="isShowDialog" />
      <!-- 设置员工角色弹窗 -->
      <AssignRole ref="assignRole" :is-show-dialog="isShowDialog" />
    </div>
  </div>
</template>

<script>
// import PageTools from '@/components/pageTools/index.vue'
import { getEmployee, delEmployee } from '@/api/employees'
// 引入枚举数据
import EmployeeEnum from '@/api/constant/employees'
import { formatDate } from '@/filters'
import { export_json_to_excel } from '@/vendor/Export2Excel'
// 新增弹窗
import AddEmployee from './comonets/add-employee.vue'
// 创建设置员工角色弹窗
import AssignRole from './comonets/assign-role.vue'
export default {
  components: {
    // PageTools
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      pageConfig: {
        page: 1,
        size: 5
      },
      total: 0,
      employeeList: [],
      isShowDialog: false,
      isShowPerm: false
    }
  },
  created() {
    this.loadPage()
  },
  methods: {
    // 创建设置员工角色弹窗
    assignRole(userId) {
      this.$refs.assignRole.getUserRoles(userId)
      this.isShowPerm = true
    },
    // 删除
    async delEmployee(id) {
      try {
        // 1. 二次询问
        await this.$confirm('是否确认删除')
        // 2. 发送请求
        await delEmployee(id)
        // 3. 提示用户
        this.$message.success('删除成功')
        // 4. 更新页面
        this.loadPage()
      } catch (error) {
        console.log(error)
      }
    },
    async exportExcel() {
      // // 后端 api 拿到的数据结构类似于
      // [
      //   { username: '王大锤', workNumber: 10001 },
      //   { username: '李翠花', workNumber: 10002 }
      // ]
      // // 实际上 excel 生成工具需要的数据格式如下
      // {
      //   header: ['用户名', '工号'],
      //   data: [
      //     ['王大锤', 10001],
      //     ['李翠花', 10002]
      //   ]
      // }

      // 导出 excel 功能
      // 1. 获取到所有数据
      const { rows } = await getEmployee({ page: 1, size: 999 })
      console.log(rows)
      // 因为需要生成的表头和数据数组顺序是一样的
      // 准备一个字典, 按顺序进行转换
      const zidian = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 用 Object.keys 函数可以生成一个对象所有 key 组成的数组
      const header = Object.keys(zidian)
      // 数据的转换其实是数组套对象换成数组套数组
      const data = rows.map(objUser => {
        const arrUser = []
        for (const zhKey in zidian) {
          // zhKey 假设遍历到姓名
          const enKey = zidian[zhKey] // username
          const value = objUser[enKey] // 王大锤

          // 生成过程中遇到一些特殊字段需要处理
          if (enKey === 'formOfEmployment') {
            // 处理到聘用形式, 就取枚举数据
            const res = EmployeeEnum.hireType.find(el => el.id === value)
            arrUser.push(res ? res.value : '')
          } else if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            arrUser.push(formatDate(value))
          } else {
            arrUser.push(value) // ['王大锤']
          }
        }
        return arrUser
      })

      // 2. 生成一个 excel 文件

      export_json_to_excel({
        header,
        data
      })
    },
    // 获取员工列表
    async loadPage() {
      const { total, rows } = await getEmployee(this.pageConfig)
      // console.log(total, rows)
      this.total = total
      this.employeeList = rows
    },
    // 分页器
    currentChange(newPage) {
      this.pageConfig.page = newPage
      this.loadPage()
    },
    formatEmployment(row, col, cellVal) {
      // return cellVal === 1 ? '正式工' : '临时工'
      // 列举出所有聘用形式的数组
      // const hireType = [
      //   { id: 1, value: '正式工' },
      //   { id: 2, value: '临时工' },
      //   { id: 3, value: '实习生' }
      // ]

      // let res = ''
      // hireType.forEach(element => {
      //   if (element.id === cellVal) {
      //     res = element.value
      //   }
      // })
      // const res = hireType.find(el => el.id === cellVal)
      const res = EmployeeEnum.hireType.find(el => el.id === cellVal)

      return res ? res.value : ''
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 180px;
  height: 88px;
  object-fit: cover;
}
</style>
